from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from models.quality import QualityTrace
from extensions import db
from datetime import datetime
import json

quality_bp = Blueprint('quality', __name__)

@quality_bp.route('/trace/list')
@login_required
def trace_list():
    # 获取查询参数
    batch_number = request.args.get('batch_number', '')
    product_name = request.args.get('product_name', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    
    # 构建查询
    query = QualityTrace.query
    if batch_number:
        query = query.filter(QualityTrace.batch_number.like(f'%{batch_number}%'))
    if product_name:
        query = query.filter(QualityTrace.product_name.like(f'%{product_name}%'))
    if start_date:
        query = query.filter(QualityTrace.production_date >= datetime.strptime(start_date, '%Y-%m-%d'))
    if end_date:
        query = query.filter(QualityTrace.production_date <= datetime.strptime(end_date, '%Y-%m-%d'))
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(QualityTrace.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('quality/trace_list.html',
                         traces=pagination.items,
                         pagination=pagination,
                         batch_number=batch_number,
                         product_name=product_name,
                         start_date=start_date,
                         end_date=end_date)

@quality_bp.route('/trace/add', methods=['GET', 'POST'])
@login_required
def trace_add():
    if request.method == 'POST':
        trace = QualityTrace(
            batch_number=request.form.get('batch_number'),
            product_name=request.form.get('product_name'),
            production_date=datetime.strptime(request.form.get('production_date'), '%Y-%m-%d'),
            expiration_date=datetime.strptime(request.form.get('expiration_date'), '%Y-%m-%d'),
            manufacturer=request.form.get('manufacturer'),
            storage_condition=request.form.get('storage_condition'),
            quality_standard=request.form.get('quality_standard'),
            inspector=request.form.get('inspector'),
            inspection_date=datetime.strptime(request.form.get('inspection_date'), '%Y-%m-%d') if request.form.get('inspection_date') else None,
            inspection_result=request.form.get('inspection_result'),
            temperature_records=json.dumps(request.form.get('temperature_records', '[]')),
            humidity_records=json.dumps(request.form.get('humidity_records', '[]')),
            notes=request.form.get('notes'),
            created_by=current_user.id
        )
        db.session.add(trace)
        db.session.commit()
        flash('质量追溯记录创建成功', 'success')
        return redirect(url_for('quality.trace_list'))
    return render_template('quality/trace_add.html')

@quality_bp.route('/trace/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def trace_edit(id):
    trace = QualityTrace.query.get_or_404(id)
    if request.method == 'POST':
        trace.product_name = request.form.get('product_name')
        trace.production_date = datetime.strptime(request.form.get('production_date'), '%Y-%m-%d')
        trace.expiration_date = datetime.strptime(request.form.get('expiration_date'), '%Y-%m-%d')
        trace.manufacturer = request.form.get('manufacturer')
        trace.storage_condition = request.form.get('storage_condition')
        trace.quality_standard = request.form.get('quality_standard')
        trace.inspector = request.form.get('inspector')
        trace.inspection_date = datetime.strptime(request.form.get('inspection_date'), '%Y-%m-%d') if request.form.get('inspection_date') else None
        trace.inspection_result = request.form.get('inspection_result')
        trace.temperature_records = json.dumps(request.form.get('temperature_records', '[]'))
        trace.humidity_records = json.dumps(request.form.get('humidity_records', '[]'))
        trace.notes = request.form.get('notes')
        
        db.session.commit()
        flash('质量追溯记录更新成功', 'success')
        return redirect(url_for('quality.trace_list'))
    return render_template('quality/trace_edit.html', trace=trace)

@quality_bp.route('/trace/view/<int:id>')
@login_required
def trace_view(id):
    trace = QualityTrace.query.get_or_404(id)
    return render_template('quality/trace_view.html', trace=trace)

@quality_bp.route('/trace/delete/<int:id>')
@login_required
def trace_delete(id):
    trace = QualityTrace.query.get_or_404(id)
    db.session.delete(trace)
    db.session.commit()
    flash('质量追溯记录删除成功', 'success')
    return redirect(url_for('quality.trace_list')) 